package com.pb.camera.work.dr_peng;

import android.content.Context;

import com.google.gson.Gson;
import com.pb.camera.R;
import com.pb.camera.application.App;
import com.pb.camera.bean.AllRoom;
import com.pb.camera.bean.DeviceMode;
import com.pb.camera.bean.GroupDevices;
import com.pb.camera.bean.UserGroup;
import com.pb.camera.bean.UserGroups;
import com.pb.camera.utils.Assert;
import com.pb.camera.utils.JsonUtil;
import com.pb.camera.utils.Logger;
import com.pb.camera.utils.Url;
import com.pb.camera.work.ControlTask;
import com.pb.camera.work.HttpException;
import com.pb.camera.work.HttpRequest;
import com.pb.camera.work.HttpUtils;
import com.pb.camera.work.RequestCallBack;
import com.pb.camera.work.ResponseInfo;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by liu fei on 2016/4/11 0011.
 * 所有与服务器交互，解析的都放到这个类下面。
 */
public class DrPengChannleWork {
    private static final String TAG = "DrPengChannleWork";

    /**
     * 获取所有的分组信息
     */
    public static void getAllRoom(final ChannleWorkInterface channleWorkInterface) {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, Url.selectAllGroups(App.getInstance().getUserId(), 0), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Logger.d(TAG, responseInfo.result);
                Assert.notNull(responseInfo.result);
                final AllRoom allRoom = JsonUtil.parseJsonToBean(responseInfo.result, AllRoom.class);
                if (allRoom.getErrcode().equals("0")) {
                    App.getInstance().setAllRoom(allRoom);
                    channleWorkInterface.onSuccess(allRoom);
                } else {
                    handleErrmsg(allRoom.getErrmsg(), channleWorkInterface);
                }
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {

            }

            @Override
            public void onStart() {

            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Logger.w(TAG, "request filed " + error.exception);
                handleErrmsg(msg, channleWorkInterface);
            }
        });
    }

    /**
     * 获取用户所在组的GruopId<br/>
     * <br/>
     *
     * @param p:查询条件<br/> &nbsp &nbsp 0:查询所有分组（自建或关注）<br/>
     *                    &nbsp &nbsp 1：查询所有自建分组<br/>
     *                    &nbsp &nbsp 2：查询有网关的自建分组<br/>
     *                    &nbsp &nbsp 3：查询无网关的自建分组<br/>
     *                    &nbsp &nbsp 4：查询所有关注分组<br/>
     */
    public static void getGroups(int p, final ChannleWorkInterface channleWorkInterface) {
        final String userId = App.getInstance().getUserId();
        Assert.isTrue(userId != null && p > 0 && p < 5);
        HttpUtils httpUtils = new HttpUtils();
        String baseUrl = Url.selectAllGroups(userId, p);
        httpUtils.send(HttpRequest.HttpMethod.GET, baseUrl, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                UserGroups userGroup = gson.fromJson(responseInfo.result, UserGroups.class);
                if (userGroup.errcode == 0) {
                    App.getInstance().setUserGroups(userGroup);
                    channleWorkInterface.onSuccess(userGroup);
                }else {
                    handleErrmsg(userGroup.errmsg,channleWorkInterface);
                }

            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                handleErrmsg(msg, channleWorkInterface);
            }
        });
    }
    /**
        获取所有的指定分组的设备信息
     */
    public static void requestDeviceGroup(int groupId, final ChannleWorkInterface channleWorkInterface) {
        String userId = App.getInstance().getUserId();
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, Url.requestGroupEquipment(groupId, userId), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                GroupDevices groupDevices = gson.fromJson(responseInfo.result, GroupDevices.class);
                if (groupDevices.errcode != 0)
                    handleErrmsg(groupDevices.errmsg,channleWorkInterface);
                channleWorkInterface.onSuccess(groupDevices);
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                handleErrmsg(msg,channleWorkInterface);
            }
        });
    }

    /**
     * 创建分组
     * @param groupName 分组名称
     * @param channleWorkInterface 接口
     */
    public static void creatGroup(String groupName, final ChannleWorkInterface channleWorkInterface) {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, Url.createGroup(groupName, App.getInstance().getUserId()), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);
                    if (jsonObject.has("errcode")) {
                        if (jsonObject.getInt("errcode") == 0)
                            channleWorkInterface.onSuccess(jsonObject.getString("gid"));
                        else if (jsonObject.has("errmsg"))
                            handleErrmsg(jsonObject.getString("errmsg"),channleWorkInterface);
                        else
                            handleErrmsg(null,channleWorkInterface);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                handleErrmsg(msg,channleWorkInterface);
            }
        });
    }

    /**
     * 添加分组的前置判断，符合条件才能允许添加
     * @param deviceMode 待添加设备的信息
     * @param channleWorkInterface 接口
     */
    public static void preJudge(DeviceMode deviceMode, final ChannleWorkInterface channleWorkInterface) {
        Assert.isTrue(deviceMode != null && channleWorkInterface != null);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, Url.firstAddEquipment(deviceMode.getDevgroupId() + "", deviceMode.getDevtype(), deviceMode.getDevid(), App.getInstance().getAccount()), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);
                    if (jsonObject.has("errcode") && jsonObject.get("errcode").equals(0))
                        channleWorkInterface.onSuccess(null);
                    else if (jsonObject.has("errmsg"))
                        channleWorkInterface.onFailed(jsonObject.getString("errmsg"));
                    else
                        channleWorkInterface.onFailed(null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {

            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                handleErrmsg(msg,channleWorkInterface);
            }
        });
    }

    /**
     *  添加设备到指定分组
     * @param deviceMode 设备详情，包含所要添加到分组的信息
     * @param channleWorkInterface 接口
     */
    public static void addDevice2Group(DeviceMode deviceMode, final ChannleWorkInterface channleWorkInterface) {
        HttpUtils httpUtils = new HttpUtils();
        String userId = App.getInstance().getUserId();
        String groupId = deviceMode.getDevgroupId();
        String deviceName = deviceMode.getDalias();
        String deviceId = deviceMode.getDevid();
        String typeId = deviceMode.getDevtype();
        String url = Url.addDevice(userId, groupId, deviceName, deviceId, typeId, null);
        httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);
                    if (jsonObject.has("errcode") && jsonObject.getInt("errcode") == 0)
                        channleWorkInterface.onSuccess(null);
                    else if (jsonObject.has("errmsg")) {
                        channleWorkInterface.onFailed(jsonObject.getString("errmsg"));
                    } else
                        channleWorkInterface.onFailed(null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                handleErrmsg(msg,channleWorkInterface);
            }
        });
    }

    /**
     * 错误信息处理
     * @param msg 错误信息
     * @param channleWorkInterface 接口
     */
    private static void handleErrmsg(String msg, ChannleWorkInterface channleWorkInterface) {
        Context context = App.getInstance();
        if (null == msg){
            channleWorkInterface.onFailed(context.getString(R.string.net_work_failed));
            return;
        }
        switch (msg){
            case "system busy":
                channleWorkInterface.onFailed(context.getString(R.string.system_busy));
                break;
            case "has been in a group":
                channleWorkInterface.onFailed(context.getString(R.string.has_been_in_group));
                break;
            case "not agree":
                channleWorkInterface.onFailed(context.getString(R.string.not_agree));
                break;
            case "not a class!":
                channleWorkInterface.onFailed(context.getString(R.string.not_a_class));
                break;
            case "add error":
                channleWorkInterface.onFailed(context.getString(R.string.add_error));
                break;
            default:
                channleWorkInterface.onFailed(context.getString(R.string.net_work_failed));
                break;
        }
    }
}

